<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <child1></child1>
      <child2></child2>
    </div>
    <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
    <script>
      //所谓的事件总线就是一个空的Vue实例，只是使用它身上$on $emit $off方法
      var eventBus = new Vue();
      const child1 = {
        template: '<button @click="sendMsg">child1向child2发出消息</button>',
        methods: {
          sendMsg() {
            //向事件总线发送一个事件msg，并携带数据
            eventBus.$emit("msg1", "child1向child2发出消息");
          },
          handleMsg(msg) {
            console.log("child1收到消息", msg);
          },
        },
        created() {
          //在实例创建后，监听事件总线发过来的msg消息，当收到消息后执行handleMsg方法
          eventBus.$on("msg2", this.handleMsg);
        },
        beforeDestroy() {
          //如果此组件被 销毁了,需要解绑,或者说取消监听
          eventBus.$off("msg2", this.handleMsg);
        },
      };
      const child2 = {
        template: '<button @click="sendMsg">child2向child1发出消息</button>',
        methods: {
          handleMsg(msg) {
            console.log("child2收到消息", msg);
          },
          sendMsg() {
            //向事件总线发送一个事件msg，并携带数据
            eventBus.$emit("msg2", "child1向child2发出消息");
          },
        },
        created() {
          //在实例创建后，监听事件总线发过来的msg消息，当收到消息后执行handleMsg方法
          eventBus.$on("msg1", this.handleMsg);
        },
        beforeDestroy() {
          //如果此组件被 销毁了,需要解绑,或者说取消监听
          eventBus.$off("msg1", this.handleMsg);
        },
      };
      var parent = new Vue({
        el: "#app",
        components: {
          child1,
          child2,
        },
      });
      parent.$destroy();
    </script>
  </body>
</html>
